const {
	Service
} = require('uni-cloud-router')
const uniID = require('uni-id')
const dbUtil = require('db-util')
const moment = require('moment-timezone');
const consts = require('consts')

module.exports = class QrcodeService extends Service {
	async create(bizCode, bindUID, validTime, count = 1) {
		let transaction = await this.db.startTransaction()
		try {
			let ids = []
			for (var i = 0; i < count; i++) {
				let data = {
					bizCode,
					bindUID,
					validTime
				}
				let res = await dbUtil.insert({
					collection: 't3ds-qrcode',
					data,
					transaction
				})
				ids.push(data._id)
			}
			await transaction.commit()
		} catch (e) {
			await transaction.rollback()
			throw e
		}
	}
	
	async consume(id) {
		let transaction = await this.db.startTransaction()
		try {
			let code = await dbUtil.getById('t3ds-qrcode', id, transaction)
			if (!code || (code.validTime && code.validTime < Date.now())) {
				throw new Error('二维码不存在或者已失效')
			}
			if (code.useUID) {
				throw new Error('二维码已失效')
			}
			if (code.bindUID && code.bindUID != this.ctx.auth.uid) {
				throw new Error('无权限')
			}
			if (code.bizCode == consts.bizCode.marketingSignIn) {
				
			} else if (code.bizCode == consts.bizCode.marketingTask) {
				await this.receiveTask(code, transaction)
			}
			await transaction.commit()
		} catch (e) {
			await transaction.rollback()
			throw e
		}
	}
	
	async receiveTask(code, transaction) {
		const dbCmd = this.db.command
		try {
			let task = await dbUtil.getOne({
				collection: 't3ds-marketing-task',
				where: {
					qrcodeIds: dbCmd.all([code._id])
				},
				field: {
					_id: true,
					deadline: true
				}
			})
			if (!task || (task.deadline && task.deadline < Date.now())) {
				throw new Error('任务不存在或者任务已过期')
			}
			await dbUtil.insert({
				collection: 't3ds-marketing-task-user',
				data: {
					uid: this.ctx.auth.uid,
					taskId: task._id
				},
				transaction
			})
		} catch (e) {
			throw e
		}
	}
}
